package trb.complexshield.bool.distance;

import no.hrp.hvrc.utils.j3d.Mat4;
import no.hrp.hvrc.utils.j3d.Vec3;
import trb.complexshield.bool.IntersectableCylinder;

public class CylinderDistance implements DistanceProducer {

    private IntersectableCylinder cylinder;
    Mat4 worldToLocal;

    public CylinderDistance(IntersectableCylinder cylinder) {
        this.cylinder = cylinder;
        worldToLocal = cylinder.getWorldToLocal();
    }

//    float sdCappedCylinder( vec3 p, vec2 h )
//    {
//        vec2 d = abs(vec2(length(p.xz),p.y)) - h;
//        return min(max(d.x,d.y),0.0) + length(max(d,0.0));
//    }

    @Override
    public float getDistance(Vec3 pos) {
        Vec3 local = worldToLocal.transformAsPoint(new Vec3(pos));
        local.y -= cylinder.getHeight() / 2f;
        Vec3 d = new Vec3(new Vec3(local.x, local.z, 0).length(), local.y, 0).absolute_();
        d.sub(cylinder.getRadius(), cylinder.getHeight() / 2f, 0);
        return Math.min(Math.max(d.x, d.y), 0f) + d.clampMin_(0f).length();
    }
}
